package com.freecloud.javabasics.classload;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Constructor;

/**
 * 自定义类加载器
 * @Author: maomao
 * @Date: 2019-11-11 09:13
 */
public class FreeClassLoader extends ClassLoader {

    private File classPathFile;

    public FreeClassLoader(){
        String classPath = FreeClassLoader.class.getResource("").getPath();
        this.classPathFile = new File(classPath);
    }


    @Override
    protected Class<?> findClass(String name){
        if(classPathFile == null) {
            return null;
        }
        File classFile = new File(classPathFile,name.replaceAll("\\.","/") + ".class");
        if(!classFile.exists()){
            return null;
        }
        String className = FreeClassLoader.class.getPackage().getName() + "." + name;

        Class<?> clazz = null;
        try(FileInputStream in = new FileInputStream(classFile);
            ByteArrayOutputStream out = new ByteArrayOutputStream()){

            byte [] buff = new byte[1024];
            int len;
            while ((len = in.read(buff)) != -1){
                out.write(buff,0,len);
            }
            clazz = defineClass(className,out.toByteArray(),0,out.size());
        }catch (Exception e){
            e.printStackTrace();
        }
        return clazz;
    }

    /**
     * 测试加载
     * @param args
     */
    public static void main(String[] args) {
        FreeClassLoader classLoader = new FreeClassLoader();
        Class<?> clazz = classLoader.findClass("FreeString");
        try {
            Constructor constructor = clazz.getConstructor();
            Object obj = constructor.newInstance();
            System.out.println("当前：" + obj.getClass().getClassLoader());

            ClassLoader classLoader1 = obj.getClass().getClassLoader();

            while (classLoader1 != null){
                classLoader1 = classLoader1.getParent();
                System.out.println("父：" + classLoader1);
            }

            SystemClassLoader.getClassLoader("com.freecloud.javabasics.classload.SystemClassLoader");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

